import { Slide } from '@libs/db/models/slide.model';
import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
import { ApiOperation, ApiTags, ApiProperty } from '@nestjs/swagger';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';

class slideCreatePostDto {
  @ApiProperty({description: '图片地址', example: '你没有提交图片地址'})
  img: string;
  @ApiProperty({description: '文章id', example: '你没有填写文章id'})
  article_id: string;
  @ApiProperty({description: '分类', example: '你没有填写轮播图的类别'})
  classification: string;
}

@ApiTags('轮播图接口')
@Controller('slides')
export class SlidesController {
  constructor(
    @InjectModel(Slide) private readonly SlideMode: ModelType<Slide>
  ){}

  @Get('page/')
  @ApiOperation({summary: '轮播图列表'})
  async selectAll(@Query() pages: any) {
    // { page: '1', pagesize: '5', sort: '-1' }
    let {page, pagesize, sort} = pages;
    // 获取总数据数
    const total = await this.SlideMode.countDocuments();

    // 计算当前页返回的是第几条数据
    const skip: number = page * pagesize - pagesize;
    pagesize = pagesize - 0;

    const data =  await this.SlideMode.find().skip(skip).limit(pagesize).sort({"_id": sort}).populate('article_id');

    return {
      total,
      content: data
    };
  }

  @Get(':id')
  @ApiOperation({summary: '根据id查找轮播图'})
  async selectId(@Param('id') id: string) {
    return await this.SlideMode.findById(id);
  }

  @Post()
  @ApiOperation({summary: '创建轮播图'})
  async create(@Body() createPostDto: slideCreatePostDto) {
    try {
      await this.SlideMode.create(createPostDto);
      return { success: '创建成功' }
    } catch (Err) {
      return { success: '创建失败' }
    }
  }

  @Put(':id')
  @ApiOperation({summary: '修改轮播图'})
  async update(@Param('id') id: string, @Body() createPostDto: slideCreatePostDto) {
    await this.SlideMode.findByIdAndUpdate(id, createPostDto);
    return {success: '修改成功'}
  }

  @Delete(':id')
  @ApiOperation({summary: '删除轮播图'})
  async remove(@Param('id') id: string) {
    await this.SlideMode.findByIdAndRemove(id)
    return {
      success: '删除成功'
    }
  }
}
